<template>
  <ul>
    <div
      v-for="(city, index) in resCity"
      class="city"
      @mouseenter="btnAdd(index)"
      @mouseleave="btnRemove(index)"
    >
      <li>
        <span>{{ city }}</span>
        <span>{{ resTem[index] }}度</span>
      </li>
      <div class="btn" v-show="isVisible[index]">
        <button @click="goSearchPage(index)">查看</button>
        <button @click="deleteCity(index)">删除</button>
      </div>
    </div>
  </ul>
</template>

<script setup>
import { watch, ref } from 'vue'
import { useRouter } from 'vue-router'

import { storeToRefs } from 'pinia'
import { useWeatherStore } from '@/stores/weather.js'
import { getAdcodeWeather } from '@/api'

const router = useRouter()

const { storageCtiys } = storeToRefs(useWeatherStore())
const { deleteCity } = useWeatherStore()
const resCity = ref([])
const resTem = ref([])
const isVisible = ref([])
const btnAdd = (index) => {
  isVisible.value[index] = true
}
const btnRemove = (index) => {
  isVisible.value[index] = false
}

//跳转用的变量
const jumpAdcode = ref([])
const jumpCity = ref([])

const getStorageCityData = async () => {
  resCity.value = []
  resTem.value = []
  for (const adcode of storageCtiys.value) {
    const data = (await getAdcodeWeather(adcode, 'base')).lives[0]
    // console.log(data)

    resCity.value.push(data.city)
    resTem.value.push(data.temperature)

    jumpAdcode.value.push(adcode)
    jumpCity.value.push(data.city)
  }
  isVisible.value.splice(
    0,
    isVisible.value.length,
    ...new Array(resCity.value.length).fill(false)
  )
}
watch(
  storageCtiys,
  async () => {
    await getStorageCityData()
  },
  { immediate: true, deep: true }
)

//跳转到搜索页面
const goSearchPage = (index) => {
  router.push({
    path: '/search',
    query: {
      adcode: jumpAdcode.value[index],
      city: jumpCity.value[index],
    },
  })
}
</script>

<style lang="scss" scoped>
.city {
  display: flex;
  // justify-content: space-between;
  align-items: center;
  gap: 20px;
  li {
    flex: 1;
    display: flex;
    justify-content: space-between;
    height: 50px;
    color: #fff;
    padding-left: 10px;
    padding-right: 10px;
    line-height: 50px;
    margin-top: 5px;
    background: #004e71;
    transition: all 1s ease-in-out;
  }
  .btn {
    flex: 0.2;
    display: flex;

    justify-content: space-around;
    gap: 10px;
    align-items: center;
    height: 40px;
    // background: #eab308;
    button {
      width: 90px;
      height: 100%;
      background: #eab308;
      border: none;
      color: #fff;
      font-size: 16px;
      cursor: pointer;
    }
  }
}
</style>
